package com.glodon.paas.exception.handler;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.glodon.paas.exception.PaasServerException;
import com.glodon.paas.exception.PaasServerExceptionFactory;
import com.glodon.paas.exception.i18n.Message;
import com.glodon.paas.util.HttpUtils;

public class WebExceptionHandler implements HandlerExceptionResolver {
	
	@Autowired
	private Message message;

	public static final Logger LOGGER = LoggerFactory.getLogger(WebExceptionHandler.class);

	@Override
	public ModelAndView resolveException(HttpServletRequest httpservletrequest,
			HttpServletResponse httpservletresponse, Object handler,
			Exception exception) {
		
		LOGGER.error(exception.getMessage(), exception);
		
		if (!(exception instanceof PaasServerException)) {
			exception = PaasServerExceptionFactory.unknownException(exception.getMessage(), exception);
		}
		
		PaasServerException ee = (PaasServerException)exception;
		String viewMessage = message.getText(ee);
		httpservletresponse.setStatus(ee.getHttpStatus());
		
		//ajax
		if(HttpUtils.isAjaxRequest(httpservletrequest) || HttpUtils.isMultiPartRequest(httpservletrequest)){
			PrintWriter os = null;
			try {
				httpservletresponse.setStatus(ee.getHttpStatus());
				os = httpservletresponse.getWriter();
				os.print(viewMessage);
			} catch (IOException e) {
				LOGGER.error(e.getMessage(), e);
			} finally {
				os.close();
			}
			return null;
		}
		else{
			httpservletrequest.setAttribute("exception", exception);
			httpservletrequest.setAttribute("viewMessage", viewMessage);
			return new ModelAndView("error");
		}
	}
}
